package com.hjm.project.accounts.accounts.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.hjm.common.utils.Utils;
import com.hjm.common.utils.request.EssentialFactors;
import com.hjm.common.utils.request.HttpClientUtils;
import com.hjm.framework.web.domain.AjaxResult;
import com.hjm.project.area.mapper.AreaMapper;
import com.hjm.project.merchantInfo.merchantInfo.domain.MerchantInfo;
import com.hjm.project.merchantInfo.merchantInfo.mapper.MerchantInfoMapper;
import com.yxhd.encrypt.EncryptUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hjm.project.accounts.accounts.mapper.AccountsMapper;
import com.hjm.project.accounts.accounts.domain.Accounts;
import com.hjm.project.accounts.accounts.service.IAccountsService;
import com.hjm.common.utils.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商户结算账户Service业务层处理
 * 
 * @author LOVE
 * @date 2020-11-19
 */
@Service
public class AccountsServiceImpl implements IAccountsService 
{
    @Autowired
    private AccountsMapper accountsMapper;
    @Autowired
    private MerchantInfoMapper merchantInfoMapper;
    @Autowired
    private AreaMapper areaMapper;

    /**
     * 查询商户结算账户
     * 
     * @param id 商户结算账户ID
     * @return 商户结算账户
     */
    @Override
    public Accounts selectAccountsById(Long id)
    {
        return accountsMapper.selectAccountsById(id);
    }



    @Override
    public Accounts selectAccounts(Accounts accounts)
    {
        return accountsMapper.selectAccounts(accounts);
    }


    /**
     * 查询商户结算账户列表
     * 
     * @param accounts 商户结算账户
     * @return 商户结算账户
     */
    @Override
    public List<Accounts> selectAccountsList(Accounts accounts)
    {
        return accountsMapper.selectAccountsList(accounts);
    }

    /**
     * 新增商户结算账户
     * 
     * @param accounts 商户结算账户
     * @return 结果
     */
    @Override
    public int insertAccounts(Accounts accounts)
    {
        return accountsMapper.insertAccounts(accounts);
    }

    /**
     * 修改商户结算账户
     * 
     * @param accounts 商户结算账户
     * @return 结果
     */
    @Override
    @Transactional
    public int updateAccounts(Accounts accounts)
    {
        return accountsMapper.updateAccounts(accounts);
    }

    /**
     * 删除商户结算账户对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteAccountsByIds(String ids)
    {
        return accountsMapper.deleteAccountsByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除商户结算账户信息
     * 
     * @param daMarker 商户结算账户ID
     * @return 结果
     */
    @Override
    public int deleteAccountsById(Long daMarker)
    {
        return accountsMapper.deleteAccountsById(daMarker);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateSettle(Map<String, String> map) throws Exception{
        MerchantInfo merchantInfo =merchantInfoMapper.selectMerchantInfoById(map.get("merno"));
        Long merchantNature=merchantInfo.getMerNature();

        Map cardBag = new HashMap();
        cardBag.put("ScreenNum",map.get("screen_num"));
        cardBag.put("ScreenName",map.get("screen_name"));
        cardBag.put("Resphone",map.get("resphone"));
        int result=0;
        //展示数据
        map.put("show_screennum",Utils.hiddenCard(map.get("screen_num")));
        map.put("show_resphone", map.get("resphone").substring(0,3)+"****"+map.get("resphone").substring(7));
        if(Integer.valueOf(map.get("nature"))==2) {
            cardBag.put("Idnumber",map.get("screen_idnum"));
            map.put("show_screenidnum",map.get("screen_idnum").substring(0,10)+"****"+map.get("screen_idnum").substring(14));
            //加密数据
            //身份证
            map.put("screen_idnum", EncryptUtils.getEncrypt(map.get("screen_idnum")));
        }

        //银行卡号
        map.put("screen_num", EncryptUtils.getEncrypt(map.get("screen_num")));
        //手机号
        map.put("resphone", EncryptUtils.getEncrypt(map.get("resphone")));
        //拼接省市区数据

        //拼接省市区数据
        Map areaMap=new HashMap();
        areaMap.put("area_type","3");
        areaMap.put("province",map.get("province"));
        areaMap.put("city",map.get("city"));
        areaMap.put("qu",map.get("area"));
        String areaName=areaMapper.getAreaName(areaMap);
       //String areaName = map.get("province_name")+","+map.get("city_name")+","+map.get("area_name");
        String bankAddress = map.get("province")+","+map.get("city")+","+map.get("area");
        map.put("bank_address", bankAddress);
        map.put("area_name", areaName);

        //商户性质(0-企业、1-个人、(3-Mpos个人、4-Mpos企业、5-大Pos个人、6-大Pos企业 - 机构商户专用)
        if (merchantNature.equals(Long.parseLong("0"))){
            if ("1".equals(map.get("nature"))){
                return AjaxResult.error("对公账户信息禁止修改");
            }
            //TODO 账户管理 >>修改账户信息(四要素)
            Map fourElements = EssentialFactors.fourElements(cardBag);
            if (!"1".equals(String.valueOf(fourElements.get("status")))) {
                return AjaxResult.error("鉴权未通过，请重新填写");
            }
            //TODO 账户管理 >>修改账户信息（钱宝）
            Map jsonObject1 = updateAccount(map,merchantInfo);
            Map responseVal1 = JSONObject.parseObject(String.valueOf(jsonObject1.get("responseVal")), Map.class);
            if (jsonObject1 != null && "A10".equals(responseVal1.get("code"))) {
                Map<String, Object> allData = getMerchantInfo(map);
                getMerInfo(allData, map, merchantInfo);
            } else {
                return AjaxResult.error("变更失败，同步上游账户信息失败");
            }
        }

        if (merchantNature.equals(Long.parseLong("1"))){
            //TODO 账户管理 >>变更账户信息(钱宝)
            Map fourElements = EssentialFactors.fourElements(cardBag);
            if (!"1".equals(fourElements.get("status").toString())) {
                return AjaxResult.error("鉴权未通过，请重新填写");
            }
            Map jsonObject2 = updateAccount(map,merchantInfo);
            Map responseVal2 = JSONObject.parseObject(String.valueOf(jsonObject2.get("responseVal")), Map.class);
            if(jsonObject2 != null && "A10".equals(responseVal2.get("code"))){
                Map<String, Object> allData = getMerchantInfo(map);
                getMerInfo(allData,map,merchantInfo);
            }else{
                return AjaxResult.error("变更失败，同步上游账户信息失败");
            }
        }
        return AjaxResult.success();
    }

    /** 传输数据 */
    public Map updateAccount(Map<String,String> map,MerchantInfo merchantInfo) throws Exception {
        Map<String, String> accounts = new HashMap();
        accounts.put("originalMid",merchantInfo.getMerno());			// 商户编号
        accounts.put("mchtNo",merchantInfo.getLdMerno());	//上级商户编号
        accounts.put("settleAcctNm",map.get("screen_name"));	// 开账户户名
        accounts.put("settleAcctNo",EncryptUtils.getDecrypt(map.get("screen_num")));	// 账户号
        accounts.put("settleBindTel",EncryptUtils.getDecrypt(map.get("resphone")));	// 银行预留手机号
        accounts.put("settleBankNm",map.get("bank_name"));		// 开户支行全称
        accounts.put("bankBranchNo",map.get("bank_num"));		// 支行行号
        String merInfo = JSON.toJSONString(accounts);
        Map<String, String> requestMap = Maps.newHashMap();
        requestMap.put("merchantInfo", merInfo);
        String json = JSON.toJSONString(requestMap);
        System.out.println(json);
        JSONObject jsonObject = HttpClientUtils.sendHttpPostJson("http://10.71.11.10:8899/updateMerchant", json);
        System.out.println("响应 ->"+ jsonObject);
        return JSONObject.toJavaObject(jsonObject, Map.class);
    }

    /** 添加sql */
    public Map<String,Object> getMerchantInfo(Map<String,String> map){
        Map<String,Object> allData = new HashMap();
        dataHandle(allData,map,"update accounts set screen_name=#{screen_name},screen_num=#{screen_num}," +
                (map.get("bank_num")!=null&&!"".equals(map.get("bank_num")) ? "bank_num=#{bank_num}," : "") +
                "bank_name=#{bank_name},bank_headname=#{bank_headname},bank_address=#{bank_address}," +
                "show_screennum=#{show_screennum},area_name=#{area_name},screen_idnum=#{screen_idnum},show_screenidnum=#{show_screenidnum}," +
                "show_resphone=#{show_resphone},nature=#{nature},resphone=#{resphone} where seq_id =#{merno} and da_marker=#{da_marker} ");
        map.put("add_man",map.get("createman"));
        allData.put("apply_type","1");
        return allData;
    }
    public void dataHandle(Map allData, Map map, String sql){
        if(allData.get("execute_sql")!=null && !"".equals(allData.get("execute_sql"))){
            StringBuilder sb = new StringBuilder(String.valueOf(allData.get("execute_sql")));
            allData.put("execute_sql",sb.append(";").append(fillSql(map,sql)).toString());
        }else{
            allData.put("execute_sql",fillSql(map,sql));
        }
    }

    public String fillSql(Map map, String sql){
        String sub = sql.substring(sql.indexOf("#{"),sql.length());
        while(sub.trim().length()>0) {
            int start = sub.indexOf("#{");
            int end = sub.indexOf("}");
            if (start == -1 || end == -1) {
                break;
            }
            String substring = sub.substring(start+2, end);
            String value = String.valueOf(map.get(substring.toLowerCase())==null ? "" : map.get(substring));
            sql = sql.replaceFirst("#\\{"+substring+"}", "'"+value+"'");
            sub = sub.substring(end+1, sub.length());
        }
        return sql;
    }

    public int getMerInfo(Map allData, Map map,MerchantInfo merchantInfo){

        allData.put("merno",String.valueOf(map.get("merno")));
        allData.put("ld_merno",merchantInfo==null?"":!StringUtils.isNotBlank(String.valueOf(merchantInfo.getLdMerno()))?"":merchantInfo.getLdMerno());
        allData.put("apply_id",merchantInfo==null?"":!StringUtils.isNotBlank(String.valueOf(merchantInfo.getApplyId()))?"":merchantInfo.getApplyId());
        allData.put("app_type",merchantInfo==null?"":!StringUtils.isNotBlank(String.valueOf(merchantInfo.getAppType()))?"":merchantInfo.getAppType());
        allData.put("status","2");
        allData.put("create_man",String.valueOf(map.get("add_man")));
        allData.put("create_time",Utils.formateDate(2));
        allData.forEach((k,v) -> System.out.println(k+"="+v));
        if("insert".equals(map.get("identity"))){
            return accountsMapper.saveMerApply(allData);
        }else{
            return accountsMapper.updateMerApply(allData);
        }

    }

}
